package com.example.inspurfabricapp;

import com.alibaba.fastjson2.JSON;
import com.example.inspurfabricapp.common.Result;
import com.example.inspurfabricapp.entity.NewWmsEntity;
import com.example.inspurfabricapp.entity.WmsEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.GatewayException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * 合约控制器
 *
 * @author lijiahao
 * @date 2024/06/26
 */
@RestController
@RequestMapping("/api/contract")
@Slf4j
public class ContractController {

    @Resource
    private Contract contract;

    @GetMapping("/{key}")
    public Result queryCatByKey(@PathVariable String key) throws GatewayException {
        byte[] cat = contract.evaluateTransaction("queryWms", key);
        String str = StringUtils.newStringUtf8((byte[]) cat);
        NewWmsEntity newWmsEntity = JSON.to(NewWmsEntity.class, str);
        return Result.ok(cat);
    }

    @PutMapping("/")
    public Result createCat(@RequestBody WmsEntity wms) throws Exception {
//        String str = String.join(",",wms.getDataList().toArray(new String[0]));
        byte[] txid = contract.createTransaction("createWms").submit(wms.getKey(), wms.getMaterialCode() ,wms.getUserId(), wms.getUserName(), wms.getDataJson());

        return Result.ok(txid);
    }

//    @PostMapping("/")
//    public Result updateCat(@RequestBody Cat cat) throws Exception {
//        byte[] bytes = contract.submitTransaction("updateCat", cat.getKey(), cat.getName(), String.valueOf(cat.getAge()), cat.getColor(), cat.getBreed());
//
//        return Result.ok(bytes);
//    }
//
//    @DeleteMapping("/{key}")
//    public Result deleteCatByKey(@PathVariable String key) throws Exception {
//        byte[] cat = contract.submitTransaction("deleteCat", key);
//
//        return Result.ok(cat);
//    }

}
